<template>
	<view>
		<view class="item" v-for="item in favoritePlaces" :key="item.objectId">
			<view class="pic">
				<image :src="item.img" mode="aspectFit"></image>
			</view>
			<view class="msg">
				<view class="name">{{ item.name }}</view>
				<view class="intro">{{ item.intro }}</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onShow
	} from 'vue';
	import {
		CONFIG
	} from '../../utils/config';

	const favoriteIds = ref([]);
	const favoritePlaces = ref([]);

	onShow(async () => {
		await getFavorites();
	});

	async function getFavorites() {
		let res = await uni.$get(CONFIG.leanCloud_url + "/1.1/classes/Favorites");
		if (res.statusCode == 200) {
			favoriteIds.value = res.data.results.map(item => item.objectId);
			favoritePlaces.value = await getSecicItems(favoriteIds.value);
		}
	}

	async function getSecicItems(ids) {
		let query = {
			"objectId": {
				"$in": ids
			}
		};
		let queryStr = JSON.stringify(query);
		let res = await uni.$get(CONFIG.leanCloud_url + "/1.1/classes/SecicItem", {
			where: queryStr
		});
		if (res.statusCode == 200) {
			return res.data.results;
		}
	}

	async function toggleFavorite(id) {
		if (favoriteIds.value.includes(id)) {
			favoriteIds.value = favoriteIds.value.filter(_id => _id !== id);
			await uni.$delete(CONFIG.leanCloud_url + "/1.1/classes/Favorites", {
				where: {
					objectId: id
				}
			});
		} else {
			favoriteIds.value.push(id);
			await uni.$post(CONFIG.leanCloud_url + "/1.1/classes/Favorites", {
				objectId: id
			});
		}
	}
</script>